package com.example.city_home_app.Activity;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.city_home_app.Bean.Down_Moment;
import com.example.city_home_app.Bean.Down_MomentComment;
import com.example.city_home_app.Bean.Down_Universe;
import com.example.city_home_app.Bean.Down__Image;
import com.example.city_home_app.Bean.MomentImg;
import com.example.city_home_app.Model.ApiModel;
import com.example.city_home_app.R;
import com.example.city_home_app.RecyclerViewAdapter.Adapter_MomentComment;
import com.example.city_home_app.RecyclerViewAdapter.Adapter_MomentImg;
import com.example.city_home_app.RecyclerViewAdapter.Adapter_PostAdd;
import com.example.city_home_app.RetrofitListener;
import com.example.city_home_app.UI.MyCircleImageView;
import com.example.city_home_app.UI.UIUtils;
import com.google.gson.Gson;
import com.squareup.picasso.Picasso;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.PicassoEngine;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.shaohui.bottomdialog.BottomDialog;

public class MomentInfoActivity extends BaseActivity {
    @BindView(R.id.toolbar_moment_info)
    Toolbar toolbarMomentInfo;
    @BindView(R.id.img_recitem_momentinfo_head)
    MyCircleImageView imgRecitemMomentinfoHead;
    @BindView(R.id.tv_recitem_momentinfo_author)
    TextView tvRecitemMomentinfoAuthor;
    @BindView(R.id.tv_recitem_momentinfo_time)
    TextView tvRecitemMomentinfoTime;
    @BindView(R.id.tv_recitem_momentinfo_content)
    TextView tvRecitemMomentinfoContent;
    @BindView(R.id.rec_recitem_momentinfo_info)
    RecyclerView recRecitemMomentinfo;
    @BindView(R.id.tv_recitem_momentinfo_commentflag)
    TextView tvRecitemMomentinfoCommentflag;
    @BindView(R.id.rec_recitem_momentinfo_comment)
    RecyclerView recRecitemMomentinfoComment;
    @BindView(R.id.tv_moment_info_commentcount)
    TextView tvMomentInfoCommentcount;
    @BindView(R.id.btn_moment_info_comment)
    Button btnMomentInfoComment;
    @BindView(R.id.tv_moment_info_likecount)
    TextView tvMomentInfoLikecount;
    @BindView(R.id.img_moment_info_like)
    ImageView imgMomentInfoLike;
    @BindView(R.id.img_momentinfo_video)
    ImageView imgMomentinfoVideo;
    @BindView(R.id.constraintLayout2)
    ConstraintLayout constraintLayout2;
    @BindView(R.id.frame_momentinfo)
    FrameLayout frameMomentinfo;

    public static MomentInfoActivity instance;
    private int momentid, userid, likecount, commentcount,deleteposition,currentimg=0,momentuserid;
    private String momentusername,videourl;
    private EditText mEditText;
    private String content;
    private Boolean islike;
    private List<Uri> list;
    private List<String> uploadimgurls = new ArrayList<>();
    private List<Down__Image> downloadimgurls = new ArrayList<>();
    private RecyclerView imgrecyclerView;
    private Adapter_MomentImg adapter_momentImg;
    private Adapter_MomentComment adapter_momentComment;
    private Adapter_PostAdd adapter_postAdd;
    private ApiModel model = new ApiModel();
    private BottomDialog dialog;
    private RetrofitListener<Down_Moment> infolistener = new RetrofitListener<Down_Moment>() {
        @Override
        public void onResponse(Down_Moment listener) {
            momentuserid = listener.getUser_id();
            momentusername = listener.getUser_name();
            tvRecitemMomentinfoAuthor.setText(listener.getUser_name());
            likecount = listener.getMoment_like();
            if (likecount == 0) {
                tvMomentInfoLikecount.setVisibility(View.GONE);
            } else {
                tvMomentInfoLikecount.setVisibility(View.VISIBLE);
                tvMomentInfoLikecount.setText(likecount + "");
            }
            tvRecitemMomentinfoTime.setText(listener.getMoment_time());
            tvRecitemMomentinfoContent.setText(listener.getMoment_content());
            Picasso.with(MomentInfoActivity.this)
                    .load("http://siminzhang.top:8088/city_home_server/public/static/posters/" + listener.getUser_headimage())
                    .into(imgRecitemMomentinfoHead);

            List<MomentImg> momentImgs = new ArrayList<>();
            getimgs(listener, momentImgs);
            if (!listener.getMoment_video().equals("")) {
                /*MomentImg b = new MomentImg();
                b.setType(2);
                b.setUrl(listener.getMoment_video());
                momentImgs.add(b);*/
                recRecitemMomentinfo.setVisibility(View.GONE);
                frameMomentinfo.setVisibility(View.VISIBLE);
                videourl = listener.getMoment_video();
                Picasso.with(MomentInfoActivity.this)
                        .load("http://siminzhang.top:8088/city_home_server/public/static/posters/" + momentImgs.get(0).getUrl())
                        .into(imgMomentinfoVideo);

            } else {
                if(!(momentImgs.size()==1&&momentImgs.get(0).getUrl().equals(""))) {
                    recRecitemMomentinfo.setVisibility(View.VISIBLE);
                    frameMomentinfo.setVisibility(View.GONE);
                    recRecitemMomentinfo.setLayoutManager(new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL));
                    adapter_momentImg = new Adapter_MomentImg(MomentInfoActivity.this);
                    recRecitemMomentinfo.setAdapter(adapter_momentImg);
                    recRecitemMomentinfo.setItemAnimator(new DefaultItemAnimator());
                    adapter_momentImg.setList(momentImgs);
                    adapter_momentImg.notifyDataSetChanged();
                }
            }

        }

        @Override
        public void onFail(String msg) {

        }
    };

    private RetrofitListener<List<Down_MomentComment>> commentlistlistener = new RetrofitListener<List<Down_MomentComment>>() {
        @Override
        public void onResponse(List<Down_MomentComment> listener) {
            if (listener.size() != 0) {
                commentcount = listener.size();
                tvMomentInfoCommentcount.setText("评论 " + commentcount);
                tvRecitemMomentinfoCommentflag.setVisibility(View.GONE);
                adapter_momentComment.setUserid(momentuserid);
                adapter_momentComment.setUsername(momentusername);
                adapter_momentComment.setList(listener);
                adapter_momentComment.notifyDataSetChanged();
            } else {
                commentcount = listener.size();
                tvMomentInfoCommentcount.setText("评论 " + commentcount);
                tvRecitemMomentinfoCommentflag.setVisibility(View.VISIBLE);
            }

        }

        @Override
        public void onFail(String msg) {

        }
    };

    @Override
    protected int getContentLayoutId() {
        return R.layout.activity_moment_info;
    }

    @Override
    protected void initViews() {
        super.initViews();
        ButterKnife.bind(this);
        Window window = MomentInfoActivity.this.getWindow();
        //如果系统5.0以上
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(0xff49afcd);
        }
        showToast();
        instance = this;
        recRecitemMomentinfoComment = (RecyclerView) findViewById(R.id.rec_recitem_momentinfo_comment);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recRecitemMomentinfoComment.setLayoutManager(layoutManager);
        adapter_momentComment = new Adapter_MomentComment(this, getSupportFragmentManager());
        recRecitemMomentinfoComment.setAdapter(adapter_momentComment);
        recRecitemMomentinfoComment.setItemAnimator(new DefaultItemAnimator());
    }

    @Override
    protected void initData() {
        super.initData();
        Intent intent = getIntent();
        momentid = intent.getIntExtra("id", 0);
        userid = BaseActivity.getUserinfo().getUserid();
        model.getmoment(momentid, infolistener);
        model.islikemoment(momentid, userid, islikelistener);

        model.getmomentcomment(momentid, commentlistlistener);
    }


    @OnClick({R.id.img_recitem_momentinfo_head, R.id.tv_recitem_momentinfo_author, R.id.btn_moment_info_comment, R.id.img_moment_info_like,R.id.img_momentinfo_video})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_recitem_momentinfo_head:
                Intent intent1 = new Intent(this,UserInfoActivity.class);
                intent1.putExtra("id",momentuserid);
                startActivity(intent1);
                break;
            case R.id.tv_recitem_momentinfo_author:
                break;
            case R.id.btn_moment_info_comment:
                showcommentDialog(1,userid);
                break;
            case R.id.img_moment_info_like:
                if (islike) {
                    model.unlikemoment(momentid, userid, unlikelistener);
                } else {
                    model.likemoment(momentid, userid, likelistener);
                }
            case R.id.img_momentinfo_video:
                Intent intent = new Intent(this, VideoActivity.class);
                intent.putExtra("url",videourl);
                intent.putExtra("title",momentusername+" 的上传视频");
                startActivity(intent);
                break;
        }
    }



    RetrofitListener<Down_Universe> islikelistener = new RetrofitListener<Down_Universe>() {
        @Override
        public void onResponse(Down_Universe listener) {
            if (listener.getMessage().equals("success")) {
                islike = true;
                imgMomentInfoLike.setImageResource(R.drawable.ic_like);
            } else {
                islike = false;
            }
        }

        @Override
        public void onFail(String msg) {

        }
    };

    RetrofitListener<Down_Universe> unlikelistener = new RetrofitListener<Down_Universe>() {
        @Override
        public void onResponse(Down_Universe listener) {
            if (listener.getMessage().equals("success")) {
                islike = false;
                imgMomentInfoLike.setImageResource(R.drawable.ic_like_no);
                if (likecount == 1) {
                    tvMomentInfoLikecount.setVisibility(View.INVISIBLE);
                    likecount = 0;
                } else {
                    tvMomentInfoLikecount.setVisibility(View.VISIBLE);
                    likecount++;
                    tvMomentInfoLikecount.setText(likecount + "");
                }

            }
        }

        @Override
        public void onFail(String msg) {

        }
    };

    RetrofitListener<Down_Universe> likelistener = new RetrofitListener<Down_Universe>() {
        @Override
        public void onResponse(Down_Universe listener) {
            if (listener.getMessage().equals("success")) {
                islike = true;
                imgMomentInfoLike.setImageResource(R.drawable.ic_like);
                if (likecount == 0) {
                    tvMomentInfoLikecount.setVisibility(View.VISIBLE);
                }
                likecount++;
                tvMomentInfoLikecount.setText(likecount + "");
            }
        }

        @Override
        public void onFail(String msg) {

        }
    };

    RetrofitListener<Down_Universe> upcommentlistener = new RetrofitListener<Down_Universe>() {
        @Override
        public void onResponse(Down_Universe listener) {
            if(listener.getMessage().equals("success")){
                UIUtils.showToast(MomentInfoActivity.this,"评论成功",UIUtils.LENGTH_SHORT);
                model.getmomentcomment(momentid,commentlistlistener);
            }
        }

        @Override
        public void onFail(String msg) {

        }
    };


    public void showcommentDialog(final int isreply,final int userid){
        dialog = BottomDialog.create(getSupportFragmentManager());
        dialog.setViewListener(new BottomDialog.ViewListener() {
            @Override
            public void bindView(final View v) {
                mEditText = (EditText)v.findViewById(R.id.edittext_dialog_newscomment_content);
                Button button = (Button)v.findViewById(R.id.btn_dialog_newscomment_send);
                Button imgbutton = (Button) v.findViewById(R.id.btn_dialog_momentcomment_upimg);
                imgrecyclerView = (RecyclerView)v.findViewById(R.id.rec_commentdialog_img);
                LinearLayoutManager layoutManager = new LinearLayoutManager(MomentInfoActivity.this);
                layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
                imgrecyclerView.setLayoutManager(layoutManager);
                adapter_postAdd = new Adapter_PostAdd(MomentInfoActivity.this,2);
                imgrecyclerView.setAdapter(adapter_postAdd);
                imgrecyclerView.setItemAnimator(new DefaultItemAnimator());
                mEditText.post(new Runnable() {
                    @Override
                    public void run() {
                        InputMethodManager imm =
                                (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.showSoftInput(mEditText, 0);
                    }
                });
                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if(!mEditText.getText().toString().equals("")){
                            dialog.dismiss();
                            if(downloadimgurls.size()!=0){
                                model.upmomentcomment(isreply,userid,momentid,mEditText.getText().toString(),downloadimgurls.get(0).getImg(),upcommentlistener);
                            }else{
                                model.upmomentcomment(isreply,userid,momentid,mEditText.getText().toString(),"",upcommentlistener);
                            }
                        }else{
                            UIUtils.showToast(MomentInfoActivity.this,"格式非法",UIUtils.LENGTH_SHORT);
                        }
                    }
                });

                imgbutton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if(currentimg==0) {
                            Matisse.from(MomentInfoActivity.this)
                                    .choose(MimeType.of(MimeType.JPEG, MimeType.PNG, MimeType.GIF))
                                    .countable(true)
                                    .maxSelectable(1)
                                    .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                                    .thumbnailScale(0.85f)
                                    .theme(R.style.Matisse_Zhihu)
                                    .imageEngine(new PicassoEngine())
                                    .capture(false)
                                    .forResult(100);
                        }else{
                            UIUtils.showToast(MomentInfoActivity.this,"你已经选择图片了",UIUtils.LENGTH_SHORT);
                        }
                    }
                });
            }
        })
                .setLayoutRes(R.layout.momentcomment_dialog)
                .setDimAmount(0.1f)
                .setCancelOutside(true)
                .setTag("评论")
                .show();
    }

    private RetrofitListener<List<Down__Image>> imgretrofitListener = new RetrofitListener<List<Down__Image>>() {
        @Override
        public void onResponse(List<Down__Image> listener) {
            for (int i = 0; i < listener.size(); i++) {
                downloadimgurls.add(listener.get(i));
            }
            uploadimgurls.clear();
            if (currentimg != 0) {
                imgrecyclerView.setVisibility(View.VISIBLE);
                adapter_postAdd.setList(downloadimgurls);
                adapter_postAdd.notifyDataSetChanged();
            } else {
                imgrecyclerView.setVisibility(View.INVISIBLE);
                adapter_postAdd.clearList();
            }
        }

        @Override
        public void onFail(String msg) {

        }
    };

    private RetrofitListener<Down_Universe> dellistener = new RetrofitListener<Down_Universe>() {
        @Override
        public void onResponse(Down_Universe listener) {
            if (listener.getMessage().equals("success")) {
                content = mEditText.getText().toString();
                content = content.replace("<img src=\"" + downloadimgurls.get(deleteposition).getImg() + "\\\"/>", "");
                mEditText.setText(content);
                downloadimgurls.remove(deleteposition);
                adapter_postAdd.setList(downloadimgurls);
                adapter_postAdd.notifyDataSetChanged();
                currentimg--;
                UIUtils.showToast(MomentInfoActivity.this, "删除成功", UIUtils.LENGTH_SHORT);
            }
        }

        @Override
        public void onFail(String msg) {

        }
    };



    private void getimgs(Down_Moment bean, List<MomentImg> list) {
        String s[] = bean.getMoment_pic().split(",");
        for (int i = 0; i < s.length; i++) {
            MomentImg b = new MomentImg();
            b.setType(1);
            b.setUrl(s[i]);
            list.add(b);
        }
    }

    public void deleteimg(int position) {
        deleteposition = position;
        ApiModel model = new ApiModel();
        List<Down__Image> list = new ArrayList<>();
        Down__Image bean = downloadimgurls.get(position);
        list.add(bean);
        Gson gson = new Gson();
        String json = gson.toJson(list);
        model.delpostimgs(json, dellistener);
    }

    private void showToast() {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

        toolbarMomentInfo = (Toolbar) findViewById(R.id.toolbar_moment_info);
        setSupportActionBar(toolbarMomentInfo);
        toolbarMomentInfo.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (data != null) {
                if (requestCode == 100 && resultCode == RESULT_OK) {
                    list = Matisse.obtainResult(data);
                    for (Uri uri : list) {
                        String path = UIUtils.getFilePathFromUri(this, uri);
                        uploadimgurls.add(path);
                        currentimg++;

                    }
                    ApiModel model = new ApiModel();
                    model.uppostimgs((ArrayList) uploadimgurls, imgretrofitListener);
                }
            }
        }
    }
}
